package com.lilosoft.core.executor;

import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.lilosoft.core.exception.MyException;

/**
 * 线程池管理器
 * @author qiusheng
 * @version 2018-05-25
 */
public class ThreadPoolManager {

    //线程操作延时
    private final int OPERATE_DELAY_TIME = 10;

    //日志异步操作的线程池
    private ScheduledThreadPoolExecutor logExecutor = new ScheduledThreadPoolExecutor(10);
    
    //主业务异步操作的线程池
    private ScheduledThreadPoolExecutor mainExecutor = new ScheduledThreadPoolExecutor(16);  
    
    //分发任务操作线程池
 //   public OrderedQueuePoolExecutor sendExcutor = new OrderedQueuePoolExecutor("分发任务队列", 10, -1);

    public static ThreadPoolManager instance = new ThreadPoolManager();

    public static ThreadPoolManager getInstance() {
    	return instance;
	}

    public void execute(TimerTask task) {
    	logExecutor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }
    
    public <V> V submit(Callable<V> task) throws MyException, InterruptedException {
		Future<V> future = mainExecutor.submit(task);
		try {
			return future.get();
		} catch (ExecutionException e) {
			Throwable cause = e.getCause();
            if (cause instanceof MyException) {
                throw (MyException) cause;
            } else {
                throw LaunderThrowable.launderThrowable(cause);
            }
		}
	}
}
